package com.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.bussiness.PoiInterface;
import com.bussiness.domain.Poi;
import com.bussiness.domain.PoiFactory;
import com.bussiness.domain.PoiTemplate;
import com.bussiness.domain.PoiTemplate.Type;
import com.bussiness.impl.PoiImpl;

/**
 * Servlet implementation class CreatePoi
 */
@WebServlet("/createpoi.html")
public class CreatePoiServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(CreatePoiServlet.class);      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreatePoiServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PoiInterface poiService = new PoiImpl();
		int tempid = 0;
		/*Parssing part*/	
		Map<String, String[]> map = request.getParameterMap();

		Map<String, String> props = new HashMap<String, String>();
		
		// Get attributtes, "name" : "Banka"
		for(String key : map.keySet()){
			logger.info("key " + key);
			String[] arr = map.get(key);
			props.put(key, arr[0]);
		}	
		
		PoiTemplate template = null; 
		List<PoiTemplate> templates = poiService.readAllPoiTemplates();
		
		try{
			tempid = Integer.parseInt(props.get("templateid"));
			template = poiService.readPoiTemplate((long) tempid);
		}catch (Exception e) {
			logger.error(e);
		}
		
		if (template == null){
			template = templates.get(0);
		}
		
		Poi poi = PoiFactory.createPoi(props,template);
		
		if (poi!=null){
			poiService.createObject(poi);
		}
		
		//put templates to jsp
		request.setAttribute("poitemplates", templates);
		request.setAttribute("props", template.getProps());
		 
		RequestDispatcher view = request.getRequestDispatcher("WEB-INF/pages/createpoi.jsp");
		view.forward(request, response);
	}

}
